// localStorage.clear()
//开始游戏点击事件
$(function() {
    $('.startgo').click(function() {
        $('.pattern').removeClass('hidden')
        score = 0;
        this.level = 1;
    });
});
//关闭音乐点击事件
$(function() {
    $('.musicstop').click(function() {
        $('audio').get(0).pause();
        $('.musicsta').removeClass('hidden')
        $('.musicstop').addClass('hidden')
    });
});
//暂停点击事件
$(function() {
    $('.sus').click(function() {
        $('audio').get(0).pause();
        $('.go').removeClass('hidden')
        clearInterval(f);
    });
});
//继续游戏点击事件
$(function() {
    $('.go').click(function() {
        $('audio').get(0).play();
        $('.go').addClass('hidden');
        if (rows != 8) {
            f = setInterval(fun, 1000);
        }
    });
});
//开启音乐点击事件
$(function() {
    $('.musicsta').click(function() {
        $('audio').get(0).play();
        $('.musicstop').removeClass('hidden')
        $('.musicsta').addClass('hidden')
    });
});
//重新排序点击事件
$(function() {
    $('.refresh').click(function() {
        changeRefresh();
    });
});
//取消模式选择点击事件
$(function() {
    $('.pattern ').click(function() {
        $('.pattern').addClass('hidden');
    });
});
//进入简单模式点击事件
$(function() {
    $('.one').click(function() {
        $('.start').addClass('hidden');
        $('.gamebox').removeClass('hidden');
        $('audio').get(0).play();
        gamecotanit.style.height = 433 + 'px';
        totalscroe.style.top = 213 + 'px';
        maxscore.style.top = 363 + 'px';
        newDom.style.top = 323 + 'px';
        goDom.style.height = 510 + 'px';
        topimg = 50; //图片的top值
        leftimg = 53; //图片的left值
        time = 91;
        types = 10; //方块种类数目
        rows = 7;
        cols = 10;
        refresh = 5;
        refreshDom.innerHTML = refresh;
        initSquareSet();
        levelDom.innerHTML = level;
        scoreDom.innerHTML = score
    });
});
//进入中等模式点击事件
$(function() {
    $('.two').click(function() {
        $('.start').addClass('hidden');
        $('.gamebox').removeClass('hidden');
        $('audio').get(0).play();
        totalscroe.style.top = 263 + 'px';
        maxscore.style.top = 410 + 'px';
        newDom.style.top = 359 + 'px';
        gamecotanit.style.height = 528 + 'px';
        goDom.style.height = 601 + 'px';
        topimg = 50; //图片的top值
        leftimg = 53; //图片的left值
        time = 111;
        types = 27; //方块种类数目
        rows = 9;
        cols = 10;
        refresh = 5;
        refreshDom.innerHTML = refresh;
        initSquareSet();
        levelDom.innerHTML = level;
        scoreDom.innerHTML = score
    });
});
//进入困难模式点击事件
$(function() {
    $('.three').click(function() {
        $('.start').addClass('hidden');
        $('.gamebox').removeClass('hidden');
        $('audio').get(0).play();
        totalscroe.style.top = 348 + 'px';
        maxscore.style.top = 96 + 'px';
        newDom.style.top = 449 + 'px';
        gamecotanit.style.height = 620 + 'px'
        goDom.style.height = 602 + 'px';
        topimg = 45; //图片的top值
        leftimg = 48; //图片的left值
        time = 131;
        types = 25; //方块种类数目
        rows = 10;
        cols = 11;
        refresh = 5;
        refreshDom.innerHTML = refresh;
        initSquareSet();
        levelDom.innerHTML = level;
        scoreDom.innerHTML = score
    });
});
//进入休闲模式点击事件
$(function() {
    $('.four').click(function() {
        $('.start').addClass('hidden');
        $('.gamebox').removeClass('hidden');
        $('audio').get(0).play();
        gamecotanit.style.height = 433 + 'px';
        totalscroe.style.top = 213 + 'px';
        maxscore.style.top = 363 + 'px';
        newDom.style.top = 323 + 'px';
        goDom.style.height = 510 + 'px';
        topimg = 45; //图片的top值
        leftimg = 53; //图片的left值
        rows = 8;
        cols = 10;
        timeDom.innerHTML = '--'
        refresh = 5;
        refreshDom.innerHTML = refresh;
        initSquareSet();
        clearInterval(f);
        levelDom.innerHTML = level;
        scoreDom.innerHTML = score
    });
});
//重新游戏点击事件
$(function() {
    $('.newplay').click(function() {
        gameoverDom.className = 'hidden'
        gamecotanit.innerHTML = '';
        if (score > window.localStorage.getItem('highestScore')) {
            window.localStorage.setItem('highestScore', score);
            maxscore.innerHTML = window.localStorage.getItem('highestScore')
        }
        this.score = 0;
        this.refresh = 5;
        this.level = 1;
        scoreDom.innerHTML = this.score;
        refreshDom.innerHTML = this.refresh;
        levelDom.innerHTML = this.level;
        switch (rows) {
            case 7:
                this.time = 91;
                break;
            case 9:
                this.time = 111;

                break;
            case 11:
                this.time = 131;
                break;
        }

        initSquareSet();

    });
});
//回到首页点击事件
$(function() {
    $('.gostart').click(function() {
        $('.start').removeClass('hidden');
        $('.gamebox').addClass('hidden');
        $('audio').get(0).pause();
        $('.pattern').addClass('hidden');
        gameoverDom.className = 'hidden'
        gamecotanit.innerHTML = '';
        clearInterval(f);
    });
});
var gamecotanit = document.getElementById('gamecotanit');//展示图片区域dom元素
var timeDom = document.getElementsByClassName('time')[0];//展示时间dom元素
var levelDom = document.getElementsByClassName('level')[0];//展示关卡dom元素
var scoreDom = document.getElementsByClassName('score')[0];//展示分数dom元素
var gameoverDom = document.getElementsByClassName('gameover')[0];//展示游戏结束样式dom元素
var totalscroe = document.getElementsByClassName('totalscore')[0];//游戏结束界面展示分数dom元素
var maxscore = document.getElementsByClassName('maxscore')[0];//展示历史最高分dom元素
var refreshDom = document.getElementsByClassName('refreshcounting')[0];//点击重新排序dom元素
var newDom = document.getElementsByClassName('newplay')[0];//点击重新游戏dom元素
var goDom = document.getElementsByClassName('go')[0];//点击继续游戏历史元素
var squareNumSetwo;//存放随机生成的数字
var squareNumSethree;
var topimg = 50; //图片的top值
var leftimg = 53; //图片的left值
var refresh = 5; //刷新次数
var score = 0; //分数
var level = 1; //关卡
var time = 130; //时间
var rows = 10; // 行数
var cols = 10; // 列数
var types = 26; //方块种类数目
var chooseOne = null; // 第一次选中的方块
var chooseTwo = null; // 第二次选中的方块
var squareSet;
var t;
var TowardEnum = {
    NONE: null,
    UP: {
        row: -1,
        col: 0
    },
    RIGHT: {
        row: 0,
        col: 1
    },
    DOWN: {
        row: 1,
        col: 0
    },
    LEFT: {
        row: 0,
        col: -1
    }
};
// 创建小方块的dom
function createSquare(value, row, col) {
    var temp = document.createElement("div");
    if (value || value == 0) {
        temp.className = 'square';
        var img = document.createElement("img");
        img.src = `./image/${value}.png`;
        temp.appendChild(img);
    } else {
        temp.innerHTML = '';
        temp.className = 'hidden'
    }
    temp.style.left = col * this.leftimg + "px";
    temp.style.top = row * this.topimg + "px";
    temp.num = value;
    temp.row = row;
    temp.col = col;
    return temp;
}
// 初始化方块数字数组
function generateSquareNumSet() {
    var tempSet = [];
    for (var i = 0; i < rows * cols / 2; i++) {
        var tempNum = Math.floor(Math.random() * types);
        tempSet.push(tempNum); // 每次push进入两个相同的方块数值
        tempSet.push(tempNum);
    }
    tempSet.sort(function() {
        return Math.random() - 0.5; // 数组乱序
    });
    return tempSet;
}
//控制改变次数
function changeRefresh() {
    if (this.refresh == 0) {} else {
        this.squareNumSethree = this.squareNumSetwo.slice(); //不加这句当连续点击刷新按钮时会出现全部空白的情况
        this.squareNumSetwo = shuffle(this.squareNumSetwo); //将剩余图片随机打乱顺序
        gamecotanit.innerHTML = ''
        for (var i = 1; i <= rows; i++) {
            for (var j = 1; j <= cols; j++) {
                var temp = createSquare(this.squareNumSetwo.pop(), i, j); //temp表示dom元素
                squareSet[i][j] = temp;
                gamecotanit.appendChild(temp);
                if (temp.num == null) {
                    gamecotanit.removeChild(temp);
                    squareSet[i][j] = null;
                }
                temp.onclick = function() {
                    if (chooseOne == null || this.num != chooseOne.num) {
                        chooseOne = this;
                    } else {
                        chooseTwo = this;
                        if (chooseOne != chooseTwo && checkLink(chooseOne.row, chooseOne.col, 0, TowardEnum.NONE, [])) { //可以消除
                            score += 10;
                            scoreDom.innerHTML = score
                            clearSquare(chooseOne.row, chooseOne.col, chooseOne.num);
                            clearSquare(chooseTwo.row, chooseTwo.col, chooseTwo.num);
                        }
                        chooseOne = null;
                        chooseTwo = null;
                    }
                    render();
                    if (checkFinish()) {
                        switch (rows) {
                            case 7:
                                time = 91;
                                break;
                            case 9:
                                time = 111;

                                break;
                            case 11:
                                time = 131;
                                break;
                        }
                        timeDom.innerHTML = time;
                        clearInterval(f);
                        level += 1;
                        levelDom.innerHTML = level;
                        initSquareSet();
                    }
                }
            }
        }
        this.squareNumSetwo = this.squareNumSethree; //如果没有这句则刷新一遍之后squareNumSetwo就为空了
        this.refresh -= 1;
        refreshDom.innerHTML = this.refresh;
    }
}
//随机打乱数组
function shuffle(a) {
    var len = a.length;
    for (var i = 0; i < len; i++) {
        var end = len - 1;
        var index = (Math.random() * (end + 1)) >> 0;
        var t = a[end];
        a[end] = a[index];
        a[index] = t;
    }
    return a;
};
// 点击之后的第一个小方块透明度变化
function render() {
    for (var i = 0; i < squareSet.length; i++) {
        for (var j = 0; j < squareSet[i].length; j++) {
            if (squareSet[i][j] && squareSet[i][j] == chooseOne) {
                squareSet[i][j].style.opacity = "0.5";
            } else if (squareSet[i][j]) {
                squareSet[i][j].style.opacity = "1";
            }
        }
    }
}
// changeTimes 转弯次数最多为2次
function checkLink(row, col, changeTimes, nowToward, path) { //当前小方块，转弯次数，路径方向(0123上右下左)，所过路径
    if (isExist(row, col) && squareSet[row][col] == chooseTwo && changeTimes <= 3) {
        return true;
    }
    if (isExist(row, col) && squareSet[row][col] != chooseOne || changeTimes > 3 ||
        row < 0 || col < 0 || row >= squareSet.length || col >= squareSet[0].length || path.indexOf(getLocaiton(row, col)) > -1) {
        path.pop();
        return false;
    }
    path.push(getLocaiton(row, col));
    return checkLink(row - 1, col, nowToward == TowardEnum.UP ? changeTimes : changeTimes + 1, TowardEnum.UP, path) //UP
        ||
        checkLink(row, col + 1, nowToward == TowardEnum.RIGHT ? changeTimes : changeTimes + 1, TowardEnum.RIGHT, path) //RIGHT
        ||
        checkLink(row + 1, col, nowToward == TowardEnum.DOWN ? changeTimes : changeTimes + 1, TowardEnum.DOWN, path) //DOWN
        ||
        checkLink(row, col - 1, nowToward == TowardEnum.LEFT ? changeTimes : changeTimes + 1, TowardEnum.LEFT, path) //LEFT
}
// 判断小方块是否在内容区域内，是否存在这个块
function isExist(row, col) {
    if (row > 0 && row < squareSet.length && col > 0 && col < squareSet[0].length && squareSet[row] && squareSet[row][col]) {
        return true;
    }
    return false;
}

function getLocaiton(row, col) {
    return row + "," + col;
}
// 消除之后，清除小方块
function clearSquare(row, col, num) {
    gamecotanit.removeChild(squareSet[row][col]);
    squareSet[row][col] = null;
    this.squareNumSetwo.forEach((item, index) => {
        if (item == num) {
            this.squareNumSetwo[index] = null //将消除掉的图片位置的num值设为null
            num += 100
        }
    });
    this.squareNumSethree = this.squareNumSetwo.slice();
}

//游戏结束
function gameover() {
  if(rows!=8){
    gameoverDom.className = 'gameover';
    totalscroe.innerHTML = score;
    if (!window.localStorage.getItem('highestScore')) {
        maxscore.innerHTML = '0'
        window.localStorage.setItem('highestScore', 0)
    }
    switch (rows) {
        case 7:
            time = 91;

            break;
        case 9:
            time = 111;
            break;
        case 11:
            time = 131;
            break;
    }
  }
}

function initSquareSet() {

    this.refresh = 5;
    maxscore.innerHTML = window.localStorage.getItem('highestScore');
    var squareNumSet = generateSquareNumSet();
    this.squareNumSetwo = squareNumSet.slice();
    // 我们会增加上下两行边界，来进行判断连接，所以我们数组的长度是 rows + 2 
    squareSet = new Array(rows + 2); // 创建一个长度为 rows + 2 的数组
    for (var i = 0; i < squareSet.length; i++) { //给代表每一行的数据项添加长度为cols+2的数组
        squareSet[i] = new Array(cols + 2);
    }
    for (var i = 1; i <= rows; i++) {
        for (var j = 1; j <= cols; j++) {
            var temp = createSquare(squareNumSet.pop(), i, j); //temp表示dom元素
            squareSet[i][j] = temp;
            gamecotanit.appendChild(temp);
            temp.onclick = function() {
                if (chooseOne == null || this.num != chooseOne.num) {
                    chooseOne = this;
                } else {
                    chooseTwo = this;
                    if (chooseOne != chooseTwo && checkLink(chooseOne.row, chooseOne.col, 0, TowardEnum.NONE, [])) { //可以消除
                        score += 10;
                        scoreDom.innerHTML = score
                        clearSquare(chooseOne.row, chooseOne.col, chooseOne.num);
                        clearSquare(chooseTwo.row, chooseTwo.col, chooseTwo.num);
                    }
                    chooseOne = null;
                    chooseTwo = null;
                }
                render();
                if (checkFinish()) {
                    switch (rows) {
                        case 7:
                            time = 91;
                            break;
                        case 9:
                            time = 111;
                            break;
                        case 11:
                            time = 131;
                            break;
                    }
                    timeDom.innerHTML = time;
                    clearInterval(f);
                    level++;
                    levelDom.innerHTML = level;
                    initSquareSet();
                }
            }
        }
    }

    f = setInterval(fun, 1000);
    // c = setInterval(clear, 1000);
}
// 判断是否结束，方块是否都消除
function checkFinish() {
    for (var i = 0; i < squareSet.length; i++) {
        for (var j = 0; j < squareSet[i].length; j++) {
            if (squareSet[i][j]) {
                return false;
            }
        }
    }
    return true;
}
//时间倒计时
function fun() {
    this.time--;
    timeDom.innerHTML = this.time
    if (this.time == 0) {
        clearInterval(f);
        gameover();
    }
};